<?php

class Exts_Gdata_Analytic2
{
    /**
     * Gapi
     *
     * @var Gapi
     */
    private $_gapi;
    protected $_defaultDateEndYesterday = true;

    public function __construct( $login, $password ) {
        $this->_gapi = new Exts_Gdata_Gapi($login,$password);
    }

    public function setDefaultDateEndToYesterday( $bool = true ) {
        $this->_defaultDateEndYesterday = (bool)$bool;
    }

    protected function _parseDateRange( $dateStart, $dateEnd ) {
        if( $dateEnd === null ) {
            if( $this->_defaultDateEndYesterday ) {
                $dateEnd = date('Y-m-d',strtotime(date('Y-m-d 00:00:00'))-1);
            }
        }
        return array($dateStart,$dateEnd);
    }

    /**
     * Returns new visits
     *
     * @param integer $profileId
     * @param string $dateStart
     * @param string $dateEnd
     * @return float
     * @todo Use combined metrics for calculation if possible
     */
    public function getNewVisits( $profileId, $dateStart = null, $dateEnd = null ) {
        list($dateStart,$dateEnd) = $this->_parseDateRange($dateStart,$dateEnd);

        $this->_gapi->requestReportData($profileId,null,array('newVisits'),null,null,$dateStart,$dateEnd);
        $returning = $this->_gapi->getNewVisits();

        $this->_gapi->requestReportData($profileId,null,array('visits'),null,null,$dateStart,$dateEnd);
        $all = $this->_gapi->getVisits();

        if( $all == 0 ) {
            return 0;
        }
        return round($returning/$all,4)*100;
    }

    public function getPageviews( $profileId, $dateStart = null, $dateEnd = null ) {
        list($dateStart,$dateEnd) = $this->_parseDateRange($dateStart,$dateEnd);

        $this->_gapi->requestReportData($profileId,null,array('pageviews'),null,null,$dateStart,$dateEnd);
        $pageviews = $this->_gapi->getPageviews();
        return $pageviews;
    }

    public function getEntrances( $profileId, $dateStart = null, $dateEnd = null ) {
        list($dateStart,$dateEnd) = $this->_parseDateRange($dateStart,$dateEnd,null,null,$dateStart,$dateEnd);

        $this->_gapi->requestReportData($profileId,null,array('entrances'),null,null,$dateStart,$dateEnd);
        return $this->_gapi->getEntrances();
    }

    public function getKeywords( $profileId, $limit = null, $dateStart = null, $dateEnd = null ) {
        list($dateStart,$dateEnd) = $this->_parseDateRange($dateStart,$dateEnd,null,null,$dateStart,$dateEnd);

        $this->_gapi->requestReportData($profileId,array('keyword'),array('entrances'),array('entrances'),null,null,null,null,$limit);
        $keywords = array();
        foreach( $this->_gapi->getResults() as $result ) {
            $keywords[] = array(
                'keyword' => (string)$result,
                'entrances' => $result->getEntrances()
            );
        }
        return $keywords;
    }
}